/*
 *  (C) Copyright 2007 Insula Tecnologia da Informacao Ltda.
 * 
 *  This file is part of Jazz.
 *
 *  Jazz is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Jazz is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Jazz.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.jazz.resolver.echo2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import nextapp.echo2.app.ListBox;
import nextapp.echo2.app.list.ListModel;
import nextapp.echo2.app.list.ListSelectionModel;

import org.openinsula.jazz.resolver.Resolver;

/**
 * {@link Resolver} implementation that resolves {@link ListBox} properties.
 * 
 * @author yanaga
 * @since 1.0
 */
public class DefaultListBoxResolver implements Resolver {

	@Override
	public Object getValue(Object bean) {
		ListBox listBox = (ListBox) bean;

		switch (listBox.getSelectionModel().getSelectionMode()) {
		case ListSelectionModel.SINGLE_SELECTION:
			return listBox.getSelectedValue();
		default:
			return listBox.getSelectedValues();
		}
	}

	@Override
	public void setValue(Object bean, Object value) {
		ListBox listBox = (ListBox) bean;

		if (value == null) {
			listBox.setSelectedIndex(-1);
		}
		else {
			int selectionMode = listBox.getSelectionMode();

			ListModel model = listBox.getModel();

			if (selectionMode == ListSelectionModel.SINGLE_SELECTION) {
				for (int i = 0; i < model.size(); i++) {
					if (value.equals(model.get(i))) {
						listBox.setSelectedIndex(i);
					}
				}
			}
			else {
				Set<Object> valueSet = new HashSet<Object>();
				if (value.getClass().isArray()) {
					valueSet.addAll(Arrays.asList((Object[]) value));
				}
				else if (value instanceof Collection<?>) {
					valueSet.addAll((Collection<?>) value);
				}
				else {
					valueSet.add(value);
				}

				List<Integer> indexList = new ArrayList<Integer>();

				for (int i = 0; i < model.size(); i++) {
					if (model.get(i) != null && valueSet.contains(model.get(i))) {
						indexList.add(i);
					}
				}

				int[] indexes = new int[indexList.size()];
				for (int i = 0; i < indexList.size(); i++) {
					indexes[i] = indexList.get(i);
				}

				listBox.setSelectedIndices(indexes);
			}
		}
	}
}
